module base {
	/**
	 * 游戏大厅服务器全局模块
	 *
	 */
    export class GameHallGlobalModule extends how.module.GlobalModule
    {
        public static response: any =
        {
            getLogin: "getLogin",//自动登陆
            onSocketOpen: egret.Event.CONNECT,//网络连接成功
            onLoginFailure: CMDConfig.GET_LOGINFAILURE,// 登陆失败返回
            onLoginSuccess: CMDConfig.GET_LOGIN_SUCCESS,//登陆成功
            onLastServerId: CMDConfig.GET_LASTSERVERID,//收到最后一次登陆服务器id
            onRoomList: CMDConfig.GET_ROOMLIST//收到房间列表
        };

        public timeOut: number = null;

        //登陆超时
        public loginTimeOut(): void
        {
            if (!AppData.getInstance().isGameHide && typeof (how.Application.currentScene) == "undefined")
            {
                how.Alert.show(LanguageConfig.noNetworkTip, () => {}, this, null, LanguageConfig.chognshiLabel);
            }
        }

        //获取登录信息
        public getLogin(): void
        {
            var account: string = egret.localStorage.getItem(StorageKeys.account);
            var password: string = egret.localStorage.getItem(StorageKeys.password);
            if(account == null || password == null)
            {
                account = base.Utils.getIMEI();
                password = account + account; // 密码存明文
                egret.localStorage.setItem(StorageKeys.account, account);
                egret.localStorage.setItem(StorageKeys.password, password);
            }

            if (typeof (how.Application.currentScene) != "undefined")
            {
                this.communicate(LoaddingGlobalModule.response.hideLoad);
                this.communicate(LoaddingGlobalModule.response.showLoad, this.loginTimeOut);
            }
            else
            {
                this.timeOut = egret.setTimeout(this.loginTimeOut, this, 10 * 1000);
            }

            AppData.getInstance().account = account;
            AppData.getInstance().token = password;
            this.hallSocket.connect(GameConfig.hallSocketHost, GameConfig.hallSocketPort);
        }
        

        //网络连接成功
        private async onSocketOpen(data: any) {
            //游戏服务器链接成功
            if (data.host == GameConfig.hallSocketHost && data.port == GameConfig.hallSocketPort)
            {
                if(egret.Capabilities.runtimeType == egret.RuntimeType.WXGAME){
                    var login:any = await platform.login();
                    if(login.code){
                        var userInfo:any = await platform.getUserInfo();
                        this.hallSocket.send(CMDConfig.SEND_REGIST, {
                            A:"mlogin",
                            code: login.code,//wx.login 
                            encryptedData: userInfo.encryptedData,// 加密数据
                            iv: userInfo.iv,// aes的iv
                            rawData: userInfo.rawData,// 校验数据
                            signature: userInfo.signature,// 校验结果
                            ChannelID: ChannelConfig.channelID,
                        });
                    }else{
                        how.Alert.show("授权失败");
                    }
                }else{
                    this.hallSocket.send(CMDConfig.SEND_LOGIN,{
                        ChannelID: ChannelConfig.channelID,
                        szAccounts: AppData.getInstance().account,
                        szPassWord: base.Utils.md5(AppData.getInstance().token),
                        machineSerial: 'bc0c96dcf907c65a742e2ce54c4df046'
                    });
                }
                AppData.getInstance().currentSocket = 0;
            }
        }

        //收到登陆成功
        private onLoginSuccess(data: any): void 
        {
            AppData.getInstance().dataInit();//初始化appData
            AppData.getInstance().userData.setData(data);//保存用户信息
        }

        // 登陆到服务器失败
        private onLoginFailure(data: any): void
        {
            if (data.lErrorCode == 217)
            {
                // 注册
                this.registerAccount(AppData.getInstance().account, AppData.getInstance().token, "");
            }
            else
            {
                how.Alert.show(LanguageConfig.error_0 + " ErrorCode:" + data.lErrorCode);
            }
        }

        //注册账号
         public registerAccount(szAccounts: string, szPassWord: string, nickname: string): void {
             var sendData = {
                 wFaceID: 0,//头像标识
                 cbGender: 1,// 用户性别
                 dwPlazaVersion: ChannelConfig.channelID,// 渠道ID
                 wCityNum: "",// 游戏类型
                 cbEnjoyType: "",// 加入类型
                 szSpreader: "",// 推广人名
                 szAccounts: szAccounts,// 登录帐号
                 szNickName: "",// 用户昵称
                 szPassWord: base.Utils.md5(szPassWord),// 登录密码
                 szTrueName: szAccounts,// 真实名称
                 szIdentity: "",// 登录密码
                 szEnjoyCode: "",// 推荐码or新手码
                 szComputerID: "bc0c96dcf907c65a742e2ce54c4df046"
             }
             this.hallSocket.send(CMDConfig.SEND_REGIST, sendData);
         }

        private onLastServerId(data: any): void 
        {
            AppData.getInstance().lastServerId = data.ServerID;
            AppData.getInstance().lastGameId = data.KindID;
            switch (data.KindID)
            {
                // case DataConfig.KIND_ID_DZPK:
                    // NewGameSceneData.getInstance().playerList = [];
                    // break;
                case DataConfig.KIND_ID_ZJH:
                    ZJHGameData.getInstance().playerList = [];
                    break;
                case DataConfig.KIND_ID_SSS:
                    ZJHGameData.getInstance().playerList = [];
                    break;

            }
        }

        //收到房间列表
        private onRoomList(data: any): void 
        {
            AppData.getInstance().setGameList(data);
            AppData.getInstance().setRoomList(data);
            AppData.getInstance().setKindClassName(data);
            this.LoginComplete();
        }

      
        //登陆完毕
        private LoginComplete(): void
        {
            //是否正在游戏中
            if (AppData.getInstance().currentGameIndex == 0)
            {
                if (this.timeOut)
                {
                    egret.clearTimeout(this.timeOut);
                }
                this.communicate(LoaddingGlobalModule.response.hideLoad);
                this.moduleManager.initModule(MainSceneModule, MainSceneView, MainSceneData);
            }
            else
            {
                this.communicate(LoaddingGlobalModule.response.showLoad);//加载页
            }
        }
    }
}

window["base"] || (window["base"] = {});
window["base"]["GameHallGlobalModule"] || (window["base"]["GameHallGlobalModule"] = base.GameHallGlobalModule);
